<template>
	<view class="page-container">
		<view class="page-header">
			<view class="header-left">
				<text class="page-title">采购入库</text>
				<text class="page-subtitle">扫码或手动入库</text>
			</view>
			<view class="header-right">
				<button class="btn btn-default" @click="handleBack">返回</button>
			</view>
		</view>

		<view v-if="loading" class="loading-state">
			<text class="loading-text">加载中...</text>
		</view>

		<view v-else-if="!requestData" class="empty-state">
			<text class="empty-text">未找到采购申请信息</text>
		</view>

		<view v-else class="content-section">
			<!-- 采购信息 -->
			<view class="info-card">
				<view class="card-title">采购信息</view>
				<view class="info-row">
					<text class="info-label">采购类型：</text>
					<text class="type-badge" :class="'type-' + requestData.item_type">{{ getItemTypeText(requestData.item_type) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">采购物品：</text>
					<text class="info-value">{{ getItemName(requestData.item_id) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">采购数量：</text>
					<text class="info-value highlight">{{ requestData.requested_quantity || 0 }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">物品编码：</text>
					<text class="info-value code-text">{{ getItemCode(requestData.item_id) }}</text>
				</view>
			</view>

			<!-- 入库方式选择 (仅对内部使用物资显示扫码选项) -->
			<view v-if="requestData.item_type === 2" class="scan-card">
				<view class="card-title">入库方式</view>
				<view class="button-group">
					<button class="btn btn-primary" @click="handleScan">扫码入库</button>
					<button class="btn btn-default" @click="handleManualStock">手动入库</button>
				</view>
				<view class="hint-text">提示：扫码入库可通过扫码枪或小程序扫描二维码/条形码</view>
			</view>

			<!-- 对外销售商品直接手动入库 -->
			<view v-else class="stock-card">
				<view class="card-title">确认入库</view>
				<view class="hint-text">此采购为对外销售商品，将直接更新商品库存</view>
				<button class="btn btn-stock" @click="handleManualStock">确认入库</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const requestId = ref('')
const requestData = ref(null)
const loading = ref(false)

onLoad((options) => {
	if (options.id) {
		requestId.value = options.id
		loadData()
	}
})

async function loadData() {
	loading.value = true
	try {
		const dhPurchaseRequests = uniCloud.importObject('dh-purchase_requests')
		const result = await dhPurchaseRequests.getPurchaseRequestById(requestId.value)
		
		if (result.code === 200) {
			requestData.value = result.data
			
			// 检查状态
			if (requestData.value.status !== 2) {
				uni.showToast({ title: '该申请尚未批准，无法入库', icon: 'none' })
				setTimeout(() => {
					uni.navigateBack()
				}, 2000)
			}
		} else {
			uni.showToast({ title: result.message || '加载失败', icon: 'error' })
		}
	} catch (error) {
		console.error('加载数据失败:', error)
		uni.showToast({ title: '加载数据失败', icon: 'error' })
	} finally {
		loading.value = false
	}
}

function handleScan() {
	// #ifdef APP-PLUS || H5
	uni.scanCode({
		success: async (res) => {
			console.log('扫码结果:', res)
			await processStock(res.result, 'scan')
		},
		fail: (err) => {
			console.error('扫码失败:', err)
			uni.showToast({ title: '扫码失败', icon: 'error' })
		}
	})
	// #endif
	
	// #ifdef MP-WEIXIN
	uni.scanCode({
		onlyFromCamera: true,
		success: async (res) => {
			console.log('扫码结果:', res)
			await processStock(res.result, 'scan')
		},
		fail: (err) => {
			console.error('扫码失败:', err)
			uni.showToast({ title: '扫码失败', icon: 'error' })
		}
	})
	// #endif
}

async function handleManualStock() {
	uni.showModal({
		title: '确认入库',
		content: `确定要将 ${requestData.value.requested_quantity} 个 ${getItemName(requestData.value.item_id)} 入库吗？`,
		success: async (res) => {
			if (res.confirm) {
				await processStock(null, 'manual')
			}
		}
	})
}

async function processStock(scanResult, method) {
	try {
		uni.showLoading({ title: '入库中...' })
		
		const userInfo = uni.getStorageSync('uni-id-pages-userInfo')
		
		// 根据采购类型处理
		if (requestData.value.item_type === 2) {
			// 内部使用物资 - 更新inventory表
			const dhInventory = uniCloud.importObject('dh-inventory')
			
			// 调整库存数量
			const adjustResult = await dhInventory.adjustInventoryQuantity(
				requestData.value.item_id._id,
				requestData.value.requested_quantity,
				1, // operation_type: 1-入库
				`采购入库 - 采购单号: ${requestId.value}`,
				method === 'scan' ? 'qrcode' : 'manual',
				''
			)
			
			if (adjustResult.code !== 200) {
				throw new Error(adjustResult.message || '库存调整失败')
			}
		} else {
			// 对外销售商品 - 更新products表
			const dhProducts = uniCloud.importObject('dh-products')
			
			// 获取当前库存
			const productResult = await dhProducts.getProductById(requestData.value.item_id._id)
			if (productResult.code !== 200) {
				throw new Error('获取商品信息失败')
			}
			
			const currentStock = productResult.data.stock_quantity || 0
			const newStock = currentStock + requestData.value.requested_quantity
			
			// 更新库存
			const updateResult = await dhProducts.updateProduct(requestData.value.item_id._id, {
				stock_quantity: newStock
			})
			
			if (updateResult.code !== 200) {
				throw new Error(updateResult.message || '更新商品库存失败')
			}
		}
		
		// 更新采购申请状态为已采购
		const dhPurchaseRequests = uniCloud.importObject('dh-purchase_requests')
		const updateResult = await dhPurchaseRequests.updatePurchaseRequest(requestId.value, {
			status: 4, // 已采购
			executed_by: userInfo._id,
			executed_time: Date.now()
		})
		
		if (updateResult.code !== 200) {
			throw new Error(updateResult.message || '更新采购状态失败')
		}
		
		uni.hideLoading()
		uni.showToast({ title: '入库成功', icon: 'success' })
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	} catch (error) {
		console.error('入库失败:', error)
		uni.hideLoading()
		uni.showToast({ title: error.message || '入库失败', icon: 'error' })
	}
}

function getItemTypeText(itemType) {
	const typeMap = {
		1: '对外销售',
		2: '内部使用'
	}
	return typeMap[itemType] || '未知'
}

function getItemName(itemId) {
	if (!itemId) return '暂无'
	if (typeof itemId === 'object') {
		return itemId.item_name || itemId.product_name || '暂无'
	}
	return '暂无'
}

function getItemCode(itemId) {
	if (!itemId) return '暂无'
	if (typeof itemId === 'object') {
		return itemId.item_code || itemId._id || '暂无'
	}
	return '暂无'
}

function handleBack() {
	uni.navigateBack()
}
</script>

<style scoped lang="scss">
.page-container {
	padding: 20px;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24px;
	background: white;
	padding: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.header-left {
	display: flex;
	flex-direction: column;
}

.page-title {
	font-size: 20px;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 4px;
}

.page-subtitle {
	font-size: 12px;
	color: #6b7280;
}

.btn {
	padding: 6px 14px;
	border-radius: 6px;
	border: none;
	cursor: pointer;
	font-size: 14px;
	font-weight: 500;
	transition: all 0.3s ease;

	&.btn-default {
		background-color: #e5e7eb;
		color: #374151;

		&:active {
			background-color: #d1d5db;
		}
	}

	&.btn-primary {
		background-color: #3b82f6;
		color: white;
		flex: 1;

		&:active {
			background-color: #2563eb;
		}
	}

	&.btn-stock {
		background-color: #10b981;
		color: white;
		width: 100%;
		padding: 12px;
		margin-top: 12px;

		&:active {
			background-color: #059669;
		}
	}
}

.loading-state,
.empty-state {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 60px 20px;
	background: white;
	border-radius: 8px;
}

.loading-text,
.empty-text {
	font-size: 14px;
	color: #6b7280;
}

.content-section {
	display: flex;
	flex-direction: column;
	gap: 16px;
}

.info-card,
.scan-card,
.stock-card {
	background: white;
	border-radius: 8px;
	padding: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.card-title {
	font-size: 16px;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 16px;
	padding-bottom: 12px;
	border-bottom: 1px solid #e5e7eb;
}

.info-row {
	display: flex;
	align-items: center;
	padding: 12px 0;
	border-bottom: 1px solid #f3f4f6;

	&:last-child {
		border-bottom: none;
	}
}

.info-label {
	font-size: 14px;
	color: #6b7280;
	width: 100px;
	flex-shrink: 0;
}

.info-value {
	font-size: 14px;
	color: #1f2937;
	flex: 1;

	&.highlight {
		font-size: 18px;
		font-weight: 600;
		color: #3b82f6;
	}

	&.code-text {
		font-family: 'Courier New', monospace;
		background-color: #f3f4f6;
		padding: 4px 8px;
		border-radius: 4px;
		font-size: 13px;
	}
}

.type-badge {
	display: inline-block;
	padding: 4px 10px;
	border-radius: 4px;
	font-size: 12px;
	font-weight: 600;

	&.type-1 {
		background-color: #dbeafe;
		color: #1e40af;
	}

	&.type-2 {
		background-color: #d1fae5;
		color: #065f46;
	}
}

.button-group {
	display: flex;
	gap: 12px;
	margin-bottom: 12px;
}

.hint-text {
	font-size: 12px;
	color: #6b7280;
	text-align: center;
	margin-top: 8px;
}
</style>

